package com.netstar.ui.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.netstar.R;
import com.netstar.download.Downloader;
import com.netstar.download.LoadInfo;
import com.netstar.model.FlowSaveModel;
import com.netstar.ui.BaseActivity;
import com.netstar.ui.adapter.FlowSaveAdapter;
import com.netstar.ui.adapter.FlowSaveAdapter.CallBack;
import com.netstar.util.ConstantSet;
import com.netstar.util.EvtLog;
import com.netstar.util.FileUtil;
import com.netstar.util.NetUtil;
import com.netstar.util.StringUtil;

public class FlowSaveActivity extends BaseActivity implements OnClickListener, OnItemClickListener {

	private static final String TAG = "FlowSaveActivity";

	private Button mBtnBack;
	private ListView mListview;
	private FlowSaveAdapter mAdapter;
	private Context mContext;
	private boolean mIsDowning;
	private String mFlg = "";
	private boolean is3GDown; // 在3G情况下下
	private int mFileSize = -1;
	private String mCurrentPath;
	// 存放各个下载器
	private Map<String, Downloader> downloaders = new HashMap<String, Downloader>();
	// 存放与下载器对应的进度条
	private Map<String, View> Views = new HashMap<String, View>();

	private ArrayList<FlowSaveModel> mList = new ArrayList<FlowSaveModel>();
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				String url = (String) msg.obj;
				int total = msg.arg1;
				int downloaded = msg.arg2;
				TextView tv = (TextView) Views.get(url);
				if (0 != total) {
					tv.setText("" + downloaded * 100 / total + "%");
				}
				if (mFileSize == total) {
					downloaders.get(url).delete(url);
					downloaders.get(url).reset();
					downloaders.remove(url);
					toast("下载完成");
					tv.setText("完成");
				}
				EvtLog.d(TAG, "total" + total);
				EvtLog.d(TAG, "mFileSize" + mFileSize);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		EvtLog.d(TAG, "onCreate");
		setContentView(R.layout.applyflow);
		initVariables();
		initViews();
		setListener();
		getData();
	}

	private void getData() {
		FlowSaveModel model1 = new FlowSaveModel();
		model1.name = "游戏";
		model1.size = "150MB";
		model1.status = "申请";
		FlowSaveModel model2 = new FlowSaveModel();
		model2.name = "应用";
		model2.size = "150MB";
		model2.status = "申请";
		FlowSaveModel model3 = new FlowSaveModel();
		model3.name = "MTV";
		model3.size = "150MB";
		model3.status = "申请";
		mList.add(model1);
		mList.add(model2);
		mList.add(model3);
		mAdapter.notifyDataSetChanged();
	}

	private void initVariables() {
		mContext = this;
		mAdapter = new FlowSaveAdapter(this, mList, new CallBack() {

			@Override
			public void onClic(View view, FlowSaveModel model) {
				String name = model.name;
				String path = "";
				String fileName = "";

				if (null != name && name.equals("游戏")) {
					path = ConstantSet.GEME_PATH;
					fileName = ConstantSet.GAME_ZIP;
				} else if (null != name && name.equals("应用")) {
					path = ConstantSet.APP_PATH;
					fileName = ConstantSet.GAME_ZIP;
				} else if (null != name && name.equals("MTV")) {
					path = ConstantSet.MTV_PATH;
					fileName = ConstantSet.MTV_ZIP;
				}
				if (!StringUtil.isNullOrEmpty(path) && !StringUtil.isNullOrEmpty(fileName)) {
					download(view, path, FileUtil.FILE_PATH + fileName);
				}
			}
		});
	}

	private void setListener() {
		mBtnBack.setOnClickListener(this);
	}

	public void initViews() {
		mBtnBack = (Button) findViewById(R.id.btn_title_left);
		mListview = (ListView) findViewById(R.id.lv_flow_save);
		mBtnBack.setVisibility(View.VISIBLE);
		mListview.setAdapter(mAdapter);
		// if (!StringUtil.isNullOrEmpty(get("game"))) {
		// mTvGameState.setText("完成");
		// } else {
		// mTvGameState.setText("申请");
		// }
		// if (!StringUtil.isNullOrEmpty(get("app"))) {
		// mTvAppState.setText("完成");
		// } else {
		// mTvAppState.setText("申请");
		// }
		// if (!StringUtil.isNullOrEmpty(get("tv"))) {
		// mTvState.setText("完成");
		// } else {
		// mTvState.setText("申请");
		// }
	}

	private void download(View v, final String filePath, final String localfile) {
		if (is3GDown) {
			NetUtil.CheckNetworkState(mContext);
		}
		DownloadTask downloadTask = new DownloadTask(v);
		downloadTask.execute(filePath, localfile, ConstantSet.DOWNLOAD_THREAD_COUNT);
	}

	class DownloadTask extends AsyncTask<String, Integer, LoadInfo> {
		Downloader downloader = null;
		View v = null;
		String urlstr = null;

		public DownloadTask(final View v) {
			this.v = v;
		}

		@Override
		protected void onPreExecute() {
			TextView btnStart = (TextView) v;
			btnStart.setText("下载中");
		}

		@Override
		protected LoadInfo doInBackground(String... params) {
			urlstr = params[0];
			mCurrentPath = urlstr;
			String localfile = params[1];
			int threadcount = Integer.parseInt(params[2]);
			// 初始化一个downloader下载器
			downloader = downloaders.get(urlstr);
			if (downloader == null) {
				downloader = new Downloader(urlstr, localfile, threadcount, FlowSaveActivity.this, mHandler);
				downloaders.put(urlstr, downloader);
			}
			if (downloader.isdownloading())
				return null;
			// 得到下载信息类的个数组成集合
			return downloader.getDownloaderInfors();
		}

		@Override
		protected void onPostExecute(LoadInfo loadInfo) {
			if (loadInfo != null) {
				// 显示进度条
				showProgress(loadInfo, urlstr, v);
				// 调用方法开始下载
				downloader.download();
			}
		}

	};

	/**
	 * 显示进度条
	 */
	private void showProgress(LoadInfo loadInfo, String url, View v) {
		mFileSize = loadInfo.getFileSize();
		int progress = loadInfo.getComplete() * 100 / mFileSize;
		((TextView) v).setText("" + progress);
		Views.put(url, v);
	}

	/**
	 * 响应暂停下载按钮的点击事件
	 */
	public void pauseDownload() {
		EvtLog.d(TAG, "暂停下载");
		if (!StringUtil.isNullOrEmpty(mCurrentPath)) {
			downloaders.get(mCurrentPath).pause();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		switch (position) {
			case 1:
				startActivity(new Intent(FlowSaveActivity.this, AppActivity.class));
				break;
			case 2:
				startActivity(new Intent(FlowSaveActivity.this, AppActivity.class));
				break;
			case 3:
				startActivity(new Intent(FlowSaveActivity.this, MtvActivity.class));
				break;
			default:
				break;
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.btn_title_left:
				finish();
				break;
			default:
				break;
		}
	}
}
